<?php
/**
 * 函数集合
 * @author   lucn30
 *
 */
namespace fast\lucn;

use think\App;
use think\Db;

class Lucn {

//字符串长度计算
function utf8_strlen($string) {
	return strlen(utf8_decode($string));
}

function utf8_strrpos($string, $needle, $offset = null) {
	if (is_null($offset)) {
		$data = explode($needle, $string);

		if (count($data) > 1) {
			array_pop($data);

			$string = join($needle, $data);

			return $this->utf8_strlen($string);
		}

		return false;
	} else {
		if (!is_int($offset)) {
			trigger_error('utf8_strrpos expects parameter 3 to be long', E_USER_WARNING);

			return false;
		}

		$string = utf8_substr($string, $offset);

		if (false !== ($position = utf8_strrpos($string, $needle))) {
			return $position + $offset;
		}

		return false;
	}
}
//字符串截取
static function utf8_substr($string, $offset, $length = null) {
	// generates E_NOTICE
	// for PHP4 objects, but not PHP5 objects
	$string = (string)$string;
	$offset = (int)$offset;

	if (!is_null($length)) {
		$length = (int)$length;
	}

	// handle trivial cases
	if ($length === 0) {
		return '';
	}

	if ($offset < 0 && $length < 0 && $length < $offset) {
		return '';
	}

	// normalise negative offsets (we could use a tail
	// anchored pattern, but they are horribly slow!)
	if ($offset < 0) {
		$strlen = strlen(utf8_decode($string));
		$offset = $strlen + $offset;

		if ($offset < 0) {
			$offset = 0;
		}
	}

	$Op = '';
	$Lp = '';

	// establish a pattern for offset, a
	// non-captured group equal in length to offset
	if ($offset > 0) {
		$Ox = (int)($offset / 65535);
		$Oy = $offset%65535;

		if ($Ox) {
			$Op = '(?:.{65535}){' . $Ox . '}';
		}

		$Op = '^(?:' . $Op . '.{' . $Oy . '})';
	} else {
		$Op = '^';
	}

	// establish a pattern for length
	if (is_null($length)) {
		$Lp = '(.*)$';
	} else {
		if (!isset($strlen)) {
			$strlen = strlen(utf8_decode($string));
		}

		// another trivial case
		if ($offset > $strlen) {
			return '';
		}

		if ($length > 0) {
			$length = min($strlen - $offset, $length);

			$Lx = (int)($length / 65535);
			$Ly = $length % 65535;

			// negative length requires a captured group
			// of length characters
			if ($Lx) {
				$Lp = '(?:.{65535}){' . $Lx . '}';
			}

			$Lp = '(' . $Lp . '.{' . $Ly . '})';
		} elseif ($length < 0) {
			if ($length < ($offset - $strlen)) {
				return '';
			}

			$Lx = (int)((-$length) / 65535);
			$Ly = (-$length)%65535;

			// negative length requires ... capture everything
			// except a group of  -length characters
			// anchored at the tail-end of the string
			if ($Lx) {
				$Lp = '(?:.{65535}){' . $Lx . '}';
			}

			$Lp = '(.*)(?:' . $Lp . '.{' . $Ly . '})$';
		}
	}

	if (!preg_match( '#' . $Op . $Lp . '#us', $string, $match)) {
		return '';
	}

	return $match[1];

}
// 截取两字符之间的字符
static function substr_between($str,$a11,$a12){

    $a11len = strlen($a11);
	$a12len = strlen($a12);
    $b = (strpos($str,$a11));
    $c = (strpos($str,$a12));
    return substr($a11,$b+$a11len,$c-$a12len); 
}


    //自动生成新尺寸 的图片

    static function resize($filename, $width, $height, $default = '' , $arg1 = 'out') {
		
	$image_dir=__ROOT__.'Uploads/image/';
	
	if (!is_file($image_dir . $filename)) {
		return;
	}

	$extension = pathinfo($filename, PATHINFO_EXTENSION);

	$old_image = $filename;
	$new_image = 'cache/' . $this->utf8_substr($filename, 0, $this->utf8_strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;

	if (!is_file($image_dir . $new_image) || (filectime($image_dir . $old_image) > filectime($image_dir . $new_image))) {
		$path = '';

		$directories = explode('/', dirname(str_replace('../', '', $new_image)));

		foreach ($directories as $directory) {
			$path = $path . '/' . $directory;

			if (!is_dir($image_dir . $path)) {
				@mkdir($image_dir . $path, 0777);
			}
		}

		list($width_orig, $height_orig) = getimagesize($image_dir . $old_image);

		if ($width_orig != $width || $height_orig != $height) {
			$image = new \Org\lucn\Image($image_dir . $old_image);
			$image->resize($width, $height , $default);
			$image->save($image_dir . $new_image);
		} else {
			copy($image_dir . $old_image, $image_dir . $new_image);
		}
	}		
		
	return 'Uploads/image/' . $new_image;
	//return $image_dir;
	}
	
//去掉格式
	static function noHtml($val){
		$val=strip_tags($val);
		$val=str_replace("&nbsp;","",$val);
		return $val;
    }

    //字符串截取
static function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=false)  
{  
    if(function_exists("mb_substr")){  
        if($suffix)  
             return mb_substr($str, $start, $length, $charset)."…";  
        else 
             return mb_substr($str, $start, $length, $charset);  
    }  
    elseif(function_exists('iconv_substr')) {  
        if($suffix)  
             return iconv_substr($str,$start,$length,$charset)."…";  
        else 
             return iconv_substr($str,$start,$length,$charset);  
    }  
    $re['utf-8']   = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";  
    $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";  
    $re['gbk']    = "/[x01-x7f]|[x81-xfe][x40-xfe]/";  
    $re['big5']   = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";  
    preg_match_all($re[$charset], $str, $match);  
    $slice = join("",array_slice($match[0], $start, $length));  
    if($suffix) return $slice."…";  
    return $slice;
}
//时间转换
static function countDownTime($unixTime)
{
	if( $unixTime == 0 )
	{
		return "";
	}

	$showTime = date('Y',$unixTime)."年".date('n',$unixTime)."月".date('j',$unixTime)."日 ".date('H:i',$unixTime);

	if( date('Y',$unixTime) == date('Y') )
	{
		$showTime = date('n',$unixTime)."月".date('j',$unixTime)."日 ".date('H:i',$unixTime);

		if( date('n.j',$unixTime) == date('n.j') )
		{
			$timeDifference = time() - $unixTime + 1;

			if( $timeDifference < 60 )
			{
				return $timeDifference."秒前";
			}

			if( $timeDifference >= 60 && $timeDifference < 3600 )
			{
				return floor($timeDifference/60)."分钟前";
			}
			
			return date('H:i',$unixTime);
		}

		if( date('n.j',($unixTime+86400)) == date('n.j') )
		{
			return "昨天 ".date('H:i',$unixTime);
		}
	}

	return $showTime;
}

// 数组转字符串，字符串转数组
static function json2str($json){
  $arr = json_decode($json,true);
  $str= implode(',',$arr);
  return $str;
}

  //取文章子分类
 static function getCategory($arr,$table = 'Category'){ //$arr为数组字符串，多种选择，比如文章和关于我们的分类选择
    if(is_array($arr)){
	    $str_pid = implode(',',$arr);
	    $where['pid'] = array('IN',$str_pid); //$str_pid为1,2,3这样的字符串
	}else{
	    $where['pid'] = $arr; //$arr为单个数字
	}
    $list=M($table)->where($where)->order('sort_order asc')->select();
    return $list;
 }
//找出文中图片，返回数组（返回例子：/oscshop/image/123.jpg、/oscshop/image/vvv.jpg，/oscshop/image/1223.jpg）这样的数组，$num为个数
static function getImg($str,$num = 0){
  $arr = [];
	//$reg = '/<[img|IMG].*?src=[\'|\"|\\\'|\\\"](.*?(?:[\.gif|\.jpg|\.jpeg|\.png]))[\'|\"|\\\'|\\\"].*?[\/]? 左边的空白没有>/';//  老的不使用了
    $preg = '/<img[^>]+?src="([^"]+)"[^>]+>/Uims';

  preg_match_all($preg,$str,$pic);//
  foreach($pic[1] as $i => $son){
  	      if($i<$num || $num == 0){$arr[] = $son;}
  	      $i++;
  }
  return $arr;
  //unset($arr);
  }
	
	/*
//下载远程文件，（自动加扩展名），$filename举例：/oscshop/uploads/image/article/20161016123
static function downFile($url,$filename){
$extNum = getimagesize($url);
if($extNum[2] == 1){$ext = 'gif';}elseif($extNum[2] == 2){$ext = 'jpg';}elseif($extNum[2] == 3){$ext = 'png';}elseif($extNum[2] == 6){$ext = 'bmp';}
$filename = $filename.'.'.$ext;
$filenamep = $_SERVER['DOCUMENT_ROOT'].$filename;
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' ); 
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false ); 
curl_setopt ( $ch, CURLOPT_URL, $url );
ob_start ();
curl_exec ( $ch );
$return_content = ob_get_contents ();
ob_end_clean (); 
$return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );

$fp=@fopen($filenamep,"a"); //将文件绑定到流   
fwrite($fp,$return_content); //写入文件
return $filename;
}
  

//创建目录
  static function mkdir($path)  
{  
    if(!is_readable($path))  
    {  
        is_file($path) or mkdir($path,0700);  
    }  
}
//下载文件
  static function downFile($url,$filename){
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' ); 
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false ); 
curl_setopt ( $ch, CURLOPT_URL, $url );
ob_start ();
curl_exec ( $ch );
$return_content = ob_get_contents ();
ob_end_clean (); 
$return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );

$fp=@fopen($filename,"a"); //将文件绑定到流   
fwrite($fp,$return_content); //写入文件
return $filename;
}
	
 //保存远程图片
 static function saveImg($content,$savePath){
	$savePath=trim($savePath); 
    //if(strpos($savePath,"{5}")>0){$savePath = str_replace ("{5}",date("ym"),$savePath);}
	$imgArr = self::getImg($content);
	$i=0;
	foreach($imgArr as $src){//
	    self::mkdir($_SERVER['DOCUMENT_ROOT'].$savePath);
		$extNum = getimagesize($src);
		if($extNum[2] == 1){$ext = 'gif';}elseif($extNum[2] == 2){$ext = 'jpg';}elseif($extNum[2] == 3){$ext = 'png';}elseif($extNum[2] == 6){$ext = 'bmp';}
		$s = date("ymdhms").'_'. rand(0,999);$fn = $savePath.$s.'.'.$ext;
		$fileName = self::downfile($src,$_SERVER['DOCUMENT_ROOT'].$fn);
		if($fileName != ''){$fn = $fn;}else{$fn = '';}
		$url1b = str_replace ($imgArr[1][$i],$fn,$url1);//带http的<img src>
		$content  = str_replace ($url1,$url1b,$content);
		$i++;
		}
	return $content;
	}
	 
 }*/
//保存远程文件
static function getImage($url,$save_dir='',$filename='',$type=0){
            if(trim($url)==''){
                return array('file_name'=>'','save_path'=>'','error'=>1);
            }
            if(trim($save_dir)==''){
                $save_dir='./';
            }
            if(trim($filename)==''){//保存文件名
                //$ext=strrchr($url,'.');
                //$extNum = pathinfo($url);
                $extNum = @getimagesize($url); //这个函数有问题，有些慢，改为下面的exif_imagetype函数
				//file_put_contents("s:/test.txt", '*********'.$extNum[2].PHP_EOL, FILE_APPEND);
				//$extNuma = exif_imagetype($url);
				//$extNum[2] = $extNuma;
                //if($extNum["extension"] == 'gif'){$ext = 'gif';}elseif($extNum["extension"] == 'jpg' || $extNum["extension"] == 'jpeg'){$ext = 'jpg';}elseif($extNum["extension"] == 'png'){$ext = 'png';}elseif($extNum["extension"] == 'webp'){$ext = 'webp';}else{$ext = 'null.jpg';}
                if($extNum[2] == 1){$ext = 'gif';}elseif($extNum[2] == 2){$ext = 'jpg';}elseif($extNum[2] == 3){$ext = 'png';}elseif($extNum[2] == 6){$ext = 'bmp';}else{$ext = 'webp';}
				//file_put_contents("s:/test.txt",serialize($extNum));
                $filename=date('Ymdhis',time()).'_'.rand(0,1000).'.'.$ext;
            }
            if(0!==strrpos($save_dir,'/')){
                $save_dir.='/';
            }
            //创建保存目录
            if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
                return array('file_name'=>'','save_path'=>'','error'=>5);
            }
            //获取远程文件所采用的方法
            if($type){
                $ch=curl_init();
                $timeout=5;
                curl_setopt($ch,CURLOPT_URL,$url);
                curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
                $img=curl_exec($ch);
                curl_close($ch);
            }else{
                ob_start();
                readfile($url);
                $img=ob_get_contents();
                ob_end_clean();
            }
            //$size=strlen($img);
            //文件大小
            $fp2=@fopen($save_dir.$filename,'a');
            fwrite($fp2,$img);
            fclose($fp2);
            unset($img,$url);
            return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
        }
		
/*========================================
           ---  TP 5.0.4 ---
========================================*/

    //取得所有分类或下属子分类。（$arr为数组分类ID，或单个分类ID，数据表默认为Category）
    static function getCate($arr, $type = 'list', $add_Pid = true, $table = 'Category'){ //$type:list或id， //add_Pid为是否加入PID
        if(is_array($arr)){
	        $str_id = implode(',',$arr);
	        $where['id'] = array('IN',$str_id); //$str_pid为1,2,3这样的字符串
	    }else{
	        $where['id'] = $arr; //$arr为单个数字
	    }
        $list = DB::name($table)->where($where)->field('id,pid,title')->order('sort_order asc')->select();
	    foreach($list as $i => $son){
	    	if($son['pid'] == 0){
	    		$where2['pid'] = $son['id'];
	    		$c = DB::name($table)->where($where2)->field('id,pid,title')->order('sort_order asc')->select();
				if($add_Pid != true){unset($list);$list = [];}//如果add_pid是true，则加入母分类。
	    		$list = array_merge($list,$c);
	    	}
			$add_Pid == true;
	    }
		if($type == 'id'){
			$arr_id = [];
			foreach($list as $i => $son){
				$arr_id[] = $son['id'];
			}
			return $arr_id;//返回ID数组
		}else{
			return $list;//返回list数组
		}
        
    }
	
	//去分类中的指定类别项
	static function getCategoryFromType($list, $value, $field = 'type'){
	    $category = [];
	    foreach($list as $i => $son){
		    if($son[$field] == $value){
			    $category[] = $son;
			}
		}
		return $category;
	}
	
	static function chinaMonth($num){
	    $china=array('一','二','三','四','五','六','七','八','九','十','十一','十二');
	    return $china[$num-1];
	}
}


